package org.szy.plugin.sys.service.impl;


import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryColumn;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.util.UpdateEntity;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.ProxyComponent;
import org.szy.core.common.page.QueryPage;
import org.szy.core.common.param.CommonStatusParam;
import org.szy.core.common.service.impl.BaseServiceImpl;
import org.szy.plugin.sys.entity.SysApp;
import org.szy.plugin.sys.mapper.SysAppMapper;
import org.szy.plugin.sys.param.SysAppQueryParam;
import org.szy.plugin.sys.service.SysAppService;

import java.util.List;

import static org.szy.plugin.sys.entity.table.SysAppTableDef.SYS_APP;

/**
 * 系统应用Service接口实现类
 *
 * @author wangbuhao
 * @since 2023-06-21 17:04:20
 **/
@ProxyComponent
public class SysAppServiceImpl extends BaseServiceImpl<SysAppMapper, SysApp> implements SysAppService {

    @Inject
    private SysAppMapper sysAppMapper;

    @Override
    public QueryWrapper qwByQuery(SysAppQueryParam param) {
        QueryWrapper qw = new QueryWrapper();
        if (StrUtil.isNotEmpty(param.getColumnField())) {
            qw.select(param.getColumnField().split(","));
        }

        if (StrUtil.isNotEmpty(param.getName())) qw.and(SYS_APP.NAME.eq(param.getName()));
        if (StrUtil.isNotEmpty(param.getCode())) qw.and(SYS_APP.CODE.eq(param.getCode()));
        if (param.getActive() != null) qw.and(SYS_APP.ACTIVE.eq(param.getActive()));
        if (param.getStatus() != null) qw.and(SYS_APP.STATUS.eq(param.getStatus()));
        return qw;
    }

    @Override
    public Page<SysApp> page(QueryPage<SysApp> page, SysAppQueryParam param) {
        QueryWrapper qw = qwByQuery(param);

        // 正序排序
        if (StrUtil.isNotEmpty(page.getAscField())) qw.orderBy(page.getAscField().split(","));
        // 倒叙排序
        if (StrUtil.isNotEmpty(page.getDescField())) {
            for (String desc : page.getDescField().split(",")) {
                qw.orderBy(new QueryColumn(desc).desc());
            }
        }

        return this.page(page, qw);
    }

    @Override
    public List<SysApp> list(SysAppQueryParam param) {
        param.setColumnField("name,code,active,status");
        QueryWrapper qw = qwByQuery(param);
        return list(qw);
    }

    @Override
    public boolean add(SysApp entity) {
        return this.save(entity);
    }

    @Override
    public boolean modifyStatus(CommonStatusParam param) {
        SysApp entity = UpdateEntity.of(SysApp.class, param.getId());
        entity.setStatus(param.getStatus());
        return sysAppMapper.update(entity) > 0;
    }

    @Override
    public boolean modifyActive(CommonStatusParam param) {
        SysApp entity = UpdateEntity.of(SysApp.class, param.getId());
        entity.setActive(param.getStatus());
        return sysAppMapper.update(entity) > 0;
    }

}
